package com.music.server.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;

import com.music.server.config.OssConfig;
import com.music.server.service.OssService;

import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.UUID;

@Service
public class OssServiceImpl implements OssService {
    @Autowired
    private OssConfig ossConfig;

    @Override
    public String upload(MultipartFile file) {

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(ossConfig.getEndpoint(), ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());
        //获取文件名
        String fileName = file.getOriginalFilename();
        //获取当前日期
        String date = new DateTime().toString("yyyy/MM/dd");
        //将当前日期 uuid 原始文件名 拼接起来组成新的文件名
        fileName = date+"/"+ UUID.randomUUID().toString().replaceAll("-","")+""+fileName;
        String url = "https://" + ossConfig.getBuckenName() + ".oss-cn-beijing.aliyuncs.com/" +fileName;

        try {
            // 上传文件流。
            ossClient.putObject(ossConfig.getBuckenName(), fileName, file.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 关闭OSSClient。
        ossClient.shutdown();
        return url;
    }
}
